package com.ip.student.service;

import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import javax.annotation.Resource;
import com.ip.student.common.config.YmlConfig;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ip.student.mapper.BaseSchoolMapper;
import com.ip.student.models.service.IBaseSchoolService;
import com.ip.student.models.bo.BaseSchoolSaveBO;
import com.ip.student.models.dto.BaseSchoolDTO;

/**
 * 学校信息控制器
 *
 * @author 张景奇
 * @Date 2025-10-29 09:02:18
 */
@DubboService
public class BaseSchoolServiceImpl extends ServiceImpl<BaseSchoolMapper, BaseSchoolDTO> implements IBaseSchoolService{

    @Resource
    private YmlConfig ymlConfig;

    @Override
    public boolean add(BaseSchoolSaveBO saveBO) {
        BaseSchoolDTO dto = new BaseSchoolDTO();
        BeanUtils.copyProperties(saveBO,dto);
        
        // 如果前端传回的ID为null，则使用雪花算法生成ID
        if (saveBO.getSchoolId() == null) {
            Long id = ymlConfig.getPkId();
            // 确保生成的ID为正数且在Integer范围内
            if (id < 0) {
                id = Math.abs(id);
            }
            // 确保ID在Integer范围内
            if (id > Integer.MAX_VALUE) {
                id = id % Integer.MAX_VALUE;
            }
            // 确保ID不为0
            if (id == 0) {
                id = 1L;
            }
            dto.setId(id);
            // 同时设置schoolId字段
            dto.setSchoolId(id.intValue());
        } else {
            dto.setId(saveBO.getSchoolId().longValue());
            dto.setSchoolId(saveBO.getSchoolId());
        }
        
        // 如果schoolCode为空，则使用雪花算法生成编码
        if (saveBO.getSchoolCode() == null || saveBO.getSchoolCode().trim().isEmpty()) {
            Long id = ymlConfig.getPkId();
            // 确保生成的ID为正数
            if (id < 0) {
                id = Math.abs(id);
            }
            // 确保ID在Integer范围内
            if (id > Integer.MAX_VALUE) {
                id = id % Integer.MAX_VALUE;
            }
            // 确保ID不为0
            if (id == 0) {
                id = 1L;
            }
            dto.setSchoolCode("SCH-" + id);
        } else {
            dto.setSchoolCode(saveBO.getSchoolCode());
        }
        
        return this.insert(dto);
    }
}